<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="渠道来源" prop="channelSource">
                <el-select v-model="queryParams.channelSource" placeholder="渠道来源" clearable style="width: 240px">
                    <el-option
                        v-for="item in channelSourceOptions"
                        :key="item.channelId"
                        :label="item.channelName"
                        :value="item.channelId"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="线索状态" prop="clueStatus">
                <el-select v-model="queryParams.clueStatus" placeholder="线索状态" clearable style="width: 240px">
                    <el-option
                        v-for="item in clueStatusOptions"
                        :key="item.dictCode"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                    v-model="dateRange"
                    style="width: 240px"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    prefix-icon="Time"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <h3 class="clue-analysis-title">线索分析</h3>

        <div id="clue-chart" style="width: 100%; height: 400px;"></div>

        <!-- 新增表格 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="time" label="时间" align="center" />
          <el-table-column prop="clueIncrement" label="线索增量" align="center" />
          <el-table-column prop="clueStock" label="线索存量" align="center" />
          <template #empty>
            <div style="text-align: center; color: #999;">暂无数据</div>
          </template>
        </el-table>

    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { getToken } from '@/utils/auth';

const queryParams = reactive({
    channelSource: null,
    clueStatus: null,
});
const dateRange = ref([]);
const showSearch = ref(true);
const loading = ref(false);

// 线索状态下拉选项
const clueStatusOptions = ref([]);
const channelSourceOptions = ref([]);

let chart = null;
const tableData = ref([]);

const initChart = () => {
    if (chart) {
        chart.dispose();
    }
    chart = echarts.init(document.getElementById('clue-chart'));
    setChartOptions([]); // 初始化时传入空数据
};

const setChartOptions = (data) => {
    const xAxisData = data.map(item => item.time);
    const incrementData = data.map(item => item.clueIncrement);
    const stockData = data.map(item => item.clueStock);

    const option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['增量数据', '存量数据'],
            bottom: '0'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xAxisData
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '增量数据',
                type: 'line',
                stack: 'Total',
                data: incrementData,
                itemStyle: {
                    color: 'orange'
                }
            },
            {
                name: '存量数据',
                type: 'line',
                stack: 'Total',
                data: stockData,
                itemStyle: {
                    color: 'blue'
                }
            }
        ]
    };
    chart.setOption(option);
};

onMounted(async () => {
    initChart();
    window.addEventListener('resize', chart.resize);
    // 获取线索状态字典
    try {
        const res = await axios.get('http://47.104.167.34:9100/prod-api/system/dict/data/type/clue_status', {
            headers: {
                Authorization: 'Bearer ' + getToken()
            }
        });
        if (res.data.code === 200 && Array.isArray(res.data.data)) {
            clueStatusOptions.value = res.data.data;
        }
    } catch (e) {
        clueStatusOptions.value = [];
    }
    // 获取渠道来源
    try {
        const res = await axios.get('http://47.104.167.34:9100/prod-api/tienchin/clue/channels', {
            headers: {
                Authorization: 'Bearer ' + getToken()
            }
        });
        if (res.data.code === 200 && Array.isArray(res.data.data)) {
            channelSourceOptions.value = res.data.data;
        }
    } catch (e) {
        channelSourceOptions.value = [];
    }
    // 初始加载数据
    handleQuery();
});

onBeforeUnmount(() => {
    if (chart) {
        chart.dispose();
    }
    window.removeEventListener('resize', chart.resize);
});

/** 搜索按钮操作 */
async function handleQuery() {
    loading.value = true;
    try {
        const params = {
            pageNum: 1,
            pageSize: 10,
            ...queryParams,
        };
        // 如果有日期范围，加入参数
        if (dateRange.value.length === 2) {
            params.beginTime = dateRange.value[0];
            params.endTime = dateRange.value[1];
        }
        const res = await axios.get('http://47.104.167.34:9100/prod-api/tienchin/analysis/clue', {
            headers: {
                Authorization: 'Bearer ' + getToken()
            },
            params
        });
        if (res.data.code === 200 && Array.isArray(res.data.rows)) {
            setChartOptions(res.data.rows);
            tableData.value = res.data.rows;
        } else {
            setChartOptions([]);
            tableData.value = [];
        }
    } catch (e) {
        setChartOptions([]);
        tableData.value = [];
    }
    loading.value = false;
}

/** 重置按钮操作 */
function resetQuery() {
    queryParams.channelSource = null;
    queryParams.clueStatus = null;
    dateRange.value = [];
    setChartOptions([]); // 重置时清空图表数据
    console.log('重置');
}
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
}

.clue-analysis-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
}

.legend-item {
    margin-right: 20px;
    font-size: 14px;
    display: inline-flex;
    align-items: center;
}

.legend-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 5px;
    display: inline-block;
}
</style>